import fs from 'fs';
import path from 'path';

let storagePath = './plugins/bililivePush-plugin/data/bilibili';   // 配置文件路径
export class ExamplePlugin extends plugin {
    constructor() {
        super({
            name: "b站功能",
            desc: "扫码登录",
            event: "message",
            priority: -Infinity,
            rule: [
                {
                    reg: /^删除我的直播推送$/,
                    fnc: "bililpush"
                }
            ]
        });
        this.storagePath = storagePath;
    }

    async bililpush(e) {
        const liveFilePath = path.join(this.storagePath, 'live.json');
        let data;

        try {
            
            const rawData = await fs.promises.readFile(liveFilePath, 'utf-8');
            data = JSON.parse(rawData);
        } catch (error) {
           logger.error('读取或解析 live.json 文件时出错:', error);
           e.reply('未知错误', true)
            return;
        }

      
        if (!data || !data.data || !e.group_id || !e.user_id) return  e.reply('未知错误', true);

        Object.keys(data.data).forEach(uid => {
            const userGroup = data.data[uid].group[e.group_id];
            if (userGroup && userGroup.includes(e.user_id)) {

                const index = userGroup.indexOf(e.user_id);
                if (index > -1) {
                    userGroup.splice(index, 1);
                }

               
                if (userGroup.length === 0) {
                    delete data.data[uid].group[e.group_id];

                    if (Object.keys(data.data[uid].group).length === 0) {
                        delete data.data[uid];
                    }
                }
            }
        });

        try {
            await fs.promises.writeFile(liveFilePath, JSON.stringify(data, null, 4), 'utf-8');
            logger.mark('live.json 更新成功');
            e.reply('成功删除当前群聊你的全部直播推送', true)
        } catch (error) {
            logger.error('更新 live.json 文件时出错:', error);
            e.reply('未知错误', true)
        }
    }
}